package com.app.couponsharelife.ui.main.me.collect

import android.content.Intent
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.hwangjr.rxbus.thread.EventThread
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.lcodecore.tkrefreshlayout.footer.LoadingView
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout

import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.CollectListBean
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.CollectListAdapter
import com.app.couponsharelife.ui.dialog.CollectCancelDialog
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.listener.OnLongClickListener
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.ui.main.home.good.GoodShareActivity
import com.app.couponsharelife.ui.viewmodel.MeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_collect.*
import kotlinx.android.synthetic.main.common_tool_bar_layout.*
import java.util.HashMap

class CollectActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_collect

    private var mViewModel: MeViewModel? = null

    private var page = 1

    /**
     * 标记下拉刷新还是上拉加载
     */
    private var isRefresh = true

    private var selectPosition = 0

    override fun initViews() {
        AppUtils.initImmersionBar(this,false)
        initToolBar()
        initRecyclerView()
        initRefreshLayout()
    }

    private fun initToolBar() {
        ivBack.setOnClickListener { finish() }
        tvToolBarTitle.text = "我的收藏"
    }

    private fun initRecyclerView() {
        mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        mRecyclerView.adapter = CollectListAdapter(arrayListOf(PageTipBean("", 0, 0)), object : OnLongClickListener {
            override fun click(isLong:Boolean,arg1: Int, arg2: Any) {
                selectPosition = arg1
                val good = arg2 as TaobaoGoodBean
                if (!isLong) {
                    val intent = Intent(this@CollectActivity, GoodDetailActivity::class.java)
                    intent.putExtra("good", good)
                    startActivity(intent)
                } else {
                    CollectCancelDialog(this@CollectActivity, R.style.DialogStyle, object : OnClickListener {
                        override fun click(arg1: Int, arg2: Any) {
                            when (arg1) {
                                0 -> cancelCollect(good.collectId)
                                else -> {
                                    val intent = Intent(this@CollectActivity, GoodShareActivity::class.java)
                                    intent.putExtra("good", good)
                                    startActivity(intent)
                                }
                            }
                        }
                    }).show()
                }
            }
        })
    }

    private fun initRefreshLayout() {
        mRefreshLayout.setFloatRefresh(true)
        mRefreshLayout.setAutoLoadMore(true)
        mRefreshLayout.setEnableLoadmore(true)
        mRefreshLayout.setEnableOverScroll(false)
        val header = ProgressLayout(this)
        header.setColorSchemeResources(R.color.act_main_bot_nav_select_text_color)
        mRefreshLayout.setHeaderView(header)
        mRefreshLayout.setBottomView(LoadingView(this))
        mRefreshLayout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = false
                loadData()
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = true
                page = 1
                loadData()
            }
        })
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(MeViewModel::class.java)
        if (!mViewModel!!.getCollectList()!!.hasObservers()) {
            mViewModel!!.getCollectList()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    handleError(parseErrorDate("数据出错啦"))
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetCollectList(hashMapOf(), false)
                        handleError(parseErrorDate(it.error!!.message))
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetCollectList(hashMapOf(), false)
                        handleError(parseErrorDate("数据出错啦"))
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetCollectList(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            handleContent(it.data.data!!)
                        } else {
                            handleError(parseErrorDate("获取失败"))
                        }
                    }
                }
            })
            mViewModel!!.cancelCollect()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshCancelCollect(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshCancelCollect(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshCancelCollect(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            if ((mRecyclerView.adapter as CollectListAdapter).list.size > selectPosition) {
                                (mRecyclerView.adapter as CollectListAdapter).list.removeAt(selectPosition)
                                if ((mRecyclerView.adapter as CollectListAdapter).list.size == 0) {
                                    (mRecyclerView.adapter as CollectListAdapter).list.add((PageTipBean("暂时没有您的任何收藏哦～", R.drawable.ic_collect_empty, 1)))
                                    (mRecyclerView.adapter as CollectListAdapter).notifyDataSetChanged()
                                } else {
                                    (mRecyclerView.adapter as CollectListAdapter).notifyItemRemoved(selectPosition)
                                }
                            }
                            showToastMsg("取消收藏成功")
                        } else {
                            showToastMsg("取消收藏失败")
                        }
                    }
                }
            })
        }
        loadData()
    }

    private fun handleContent(data: CollectListBean) {
        if (page == 1 && isRefresh) {
            mRefreshLayout.finishRefreshing()
        } else
            mRefreshLayout.finishLoadmore()
        if (data.recordss.isNotEmpty()) {
            page++
            (mRecyclerView.adapter as CollectListAdapter).setData(data.recordss, page)
        } else {
            handleError(PageTipBean(if (page == 1) "暂时没有您的任何收藏哦～" else "暂无更多收藏记录", R.drawable.ic_collect_empty, 1))
        }
    }

    private fun handleError(pageTipBean: PageTipBean) {
        if (page == 1) {
            if (isRefresh) mRefreshLayout.finishRefreshing() else mRefreshLayout.finishLoadmore()
            if ((mRecyclerView.adapter as CollectListAdapter).list[0] is PageTipBean) {
                ((mRecyclerView.adapter as CollectListAdapter).list[0] as PageTipBean).tip = pageTipBean.tip
                ((mRecyclerView.adapter as CollectListAdapter).list[0] as PageTipBean).status = pageTipBean.status
                ((mRecyclerView.adapter as CollectListAdapter).list[0] as PageTipBean).src = pageTipBean.src
                (mRecyclerView.adapter as CollectListAdapter).notifyItemChanged(0)
            }
        } else {
            mRefreshLayout.finishLoadmore()
            showToastMsg(pageTipBean.tip)
        }
    }

    private fun loadData() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["pageNo"] = page.toString()
        mViewModel?.freshGetCollectList(map, true)
    }

    private fun cancelCollect(collectId: String) {
        if (collectId == "") {
            showToastMsg("数据错误，请退出重试")
            return
        }
        val map = HashMap<String, String>()
        map["collectId"] = collectId
        mViewModel?.freshCancelCollect(map, true)
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = [(Tag("freshCancelCollect"))])
    fun receiveData(position: String) {
        if ((mRecyclerView.adapter as CollectListAdapter).list.size > selectPosition) {
            (mRecyclerView.adapter as CollectListAdapter).list.removeAt(selectPosition)
            if ((mRecyclerView.adapter as CollectListAdapter).list.size == 0) {
                (mRecyclerView.adapter as CollectListAdapter).list.add((PageTipBean("暂时没有您的任何收藏哦～", R.drawable.ic_collect_empty, 1)))
                (mRecyclerView.adapter as CollectListAdapter).notifyDataSetChanged()
            } else {
                (mRecyclerView.adapter as CollectListAdapter).notifyItemRemoved(selectPosition)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}
